import cv2
import numpy as np

# 读取图像
image = cv2.imread('Crayon Shin-chan.jpg')
if image is None:
    print("无法读取图像，请检查路径")
    exit()

# 转换到HSV颜色空间
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# 黄色范围（保持你之前的设置，确保掩膜正确提取目标区域）
lower_yellow = np.array([22, 230, 155])
upper_yellow = np.array([25, 255, 255])

# 提取黄色区域
yellow_mask = cv2.inRange(hsv, lower_yellow, upper_yellow)

# 形态学处理（保留你之前的参数，确保掩膜图形完整）
kernel = np.ones((5, 5), np.uint8)
yellow_mask = cv2.morphologyEx(yellow_mask, cv2.MORPH_CLOSE, kernel)
yellow_mask = cv2.morphologyEx(yellow_mask, cv2.MORPH_OPEN, kernel)

# 查找轮廓（获取掩膜中所有图形的轮廓）
contours, _ = cv2.findContours(yellow_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 遍历所有轮廓，对每个图形绘制最小外接矩形
for cnt in contours:
    # 跳过面积极小的噪点轮廓（可选，根据需求调整）
    area = cv2.contourArea(cnt)
    if area < 3600:  # 可根据实际情况修改，过滤微小噪点
        continue

    # 计算最小外接矩形并绘制
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect).astype(int)
    cv2.drawContours(image, [box], 0, (0, 255, 0), 2)  # 绿色框

# 显示结果
cv2.imshow("Yellow Mask", yellow_mask)
cv2.imwrite('Mask.jpg', yellow_mask)
cv2.imshow("All Shapes Boxed", image)
cv2.imwrite('all_boxed_result.jpg', image)
cv2.waitKey(0)
